package cn.imvc.app.models;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;
import cn.imvc.app.entities.PriceClass;
import cn.imvc.app.repositories.PriceClassRepository;
import cn.imvc.core.DialogBean;
import cn.imvc.core.Render;
import cn.imvc.data.domain.ViewRequest;

/**
 * 
 * @author zhy
 * @date 2016年7月20日上午11:18:20
 *
 */
@Service
public class PriceClassModelImpl implements PriceClassModel{

	@Autowired
	PriceClassRepository priceClassRepository;
	@Autowired
	RefRelationModel refRelationModel;
	
	public List<PriceClass> findPriceClass() {
		
		return (List<PriceClass>)priceClassRepository.findAll();
	}

	public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> getRequestMap() {
		
		return null;
	}

	public Page<PriceClass> find(ViewRequest viewRequest) {
		
		return priceClassRepository.findAll(viewRequest);
	}

	public PriceClass get(int id) {
		
		return priceClassRepository.getOne(id);
	}

	public int save(PriceClass priceClass) {

		String code = priceClass.getCode();
		String name = priceClass.getName();
		List<PriceClass> pc = priceClassRepository.findByCode(code);
		List<PriceClass> pn= priceClassRepository.findByName(name);
		
		if(pc.size()>0){
		   return 0;
		}else if(pn.size()>0){
			return -1;
		}
		priceClassRepository.saveAndFlush(priceClass);
		return 1;
	}

	public int update(int id, PriceClass priceClass) {
		PriceClass pc = priceClassRepository.getOne(id);
		String code = priceClass.getCode();
		String name = priceClass.getName();
		List<PriceClass> pcList = priceClassRepository.findByCode(code);
		List<PriceClass> pnList = priceClassRepository.findByName(name);
        if(pcList.size()>0&&!code.equals(pc.getCode())){
        	return 0;
        }
		if(pnList.size()>0&&!name.equals(pc.getName())){
			return -1;
		}

		BeanUtils.copyProperties(priceClass, pc, new String[]{"id"});
		priceClassRepository.saveAndFlush(pc);
		return  1;  
	}

	public void deleteBatch(int[] ids) {
	
		for (int id : ids) {
			delete(id);
		}
	}

	public String delete(int id) {
		 String result = refRelationModel.deleteDateCheck("Price_Class", "id", id);
		    if(result.equals("")){
		    	priceClassRepository.delete(id);
		    	return "";
		    }else{
		    	return result;
		    }
	}


}
